# from rest_framework.generics import ListCreateAPIView, ListAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from goods.models import Brand, Group
from goods.serializer import *
from rest_framework_jwt.utils import jwt_decode_handler
import os
from django.conf import settings
from rest_framework.generics import *



# 品牌
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 上传图片
class UploadLogoAPIView(APIView):
    def post(self,request):
        print('上传图片数据：',request.data)
        # 获取前端传入的数据
        token = request.data.get('token')
        file = request.data.get('file')
        # 认证用户的登录信息
        try:
            payload = jwt_decode_handler(token)

        except:
            return Response({'code':401,'msg':'用户没有认证'},status=401)

        # 保存上传的数据
        static_path = 'static/images/logos'
        # 获取目录的据对路径
        file_dir = os.path.join(settings.BASE_DIR,static_path)
        file_name = os.path.join(file_dir,file.name)

        # 打开以上文件写入字节流
        with open(file_name,'wb') as f:
            f.write(file.file.read())

        # 返回响应
        return Response({'code':200,'msg':'上传成功','static_path':static_path},status=200)

# 频道组的视图
class GroupAPIView(ListCreateAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer

    # def create(self,request,*args,**kwargs):
    #     print('前端输入的数据',request.data)
    #     ser = self.get_serializer(data = request.data)
    #     if ser.is_valid():
    #         return Response(request.data,status=201)
    #     else:
    #         return Response({'msg':ser.error_message},status=400)


# 加载所有商品类别
class CateAPIView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer

# 商品子类别
class SubCates(RetrieveAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    # retrieve检索
    def retrieve(self, request, *args, **kwargs):
        # 查询父类别的对象
        p_object = self.get_object()
        # 反向查询父类别的子类别
        sub_cates = p_object.subs.all()
        # 序列化输出子类别
        sub_cates_ser = self.get_serializer(sub_cates,many=True)
        # 返回响应
        return Response(sub_cates_ser.data)

# 频道组详情(检索 更新 删除)
class GroupInfo(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 加载一级类别
class FirstCate(ListCreateAPIView):
    queryset = Cate.objects.filter(cid=None)
    serializer_class = CateSer

# SKU
class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    # 添加商品去重
    def create(self, request, *args, **kwargs):
        # 获取前端数据
        name = request.data.get('name')
        # 判断改名称是否在数据库
        sku = SKU.objects.filter(name=name)
        if sku:
            return Response({'code':400,'msg':'该商品已存在'})
        # 添加
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)  # 数据校验
        ser.save()  # 保存数据
        return Response({'code':200,'msg':'添加成功'},status=201)

# spu
# class ListSPU(ModelViewSet):
#     queryset = SPU.objects.all()
#     serializer_class = SPUSer

# spu
class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 展示商品规格
class SPUSpecs(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 规格选项值的展示
class SpecValue(ModelViewSet):
    queryset = SpecValue.objects.all()
    serializer_class = ValueSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 商品图片
class SKUImages(ModelViewSet):
    queryset = SKUImg.objects.all()
    serializer_class = SKUImageSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    # 重写create方法 加入去重机制
    def create(self,request,*args,**kwargs):
        # 1.接收前端数据
        sku_id = request.data.get('sku')
        image = request.data.get('image')

        # 2.判断当前商品是否存在
        result = SKUImg.objects.filter(sku_id=sku_id,image=image)
        if result:
            return Response({'code':400,'msg':'该商品图片已经存在'})
        # 3.添加商品图片
        SKUImg.objects.create(sku_id=sku_id,image=image)
        return Response({'code':'200','msg':'图片添加成功'},status=201)

# 上传商品图片的视图
class UploadSKUImage(APIView):
    def post(self,request):
        # 接收前端数据
        print('前端上传的数据',request.data)
        token = request.data.get('token')
        file = request.data.get('file')
        # 2.验证token口令
        try:
            payload = jwt_decode_handler(token)
        except:
            return Response({'code':401,'msg':'未认证'})

        # 3.获取相关的路径
        file_name = file.name
        static_path = 'static/images/phone'
        file_path = os.path.join(settings.BASE_DIR,static_path)
        # 判断文件目录是否存在 不存在则创建目录
        if not os.path.exists(file_path):
            # 创建该目录
            os.makedirs(file_path)
        # 获取图片的完整绝对路径
        ful_path = os.path.join(file_path,file_name)

        # 4.保存图片
        with open(ful_path,'wb')as f:
            f.write(file.file.read())
        # 返回响应
        return Response({'code':200,'msg':'上传图片成功','static_path':static_path})

from qiniu import Auth
access_key = 'pgHUbmSvM-QWQYd-B1aTybqpjYWtGfLRMt4shtwW'
secret_key = 'UZS2ScUNIHSCLHZenEKJdvxF2jhrvk2Tj8kNv00X'
# 七牛云tokrn
class QiNiuToken(APIView):
    def get(self,reqest):
        # 生成token
        token = self.gen_token()
        return Response({'code':200,'msg':'生成七牛云token成功','token':token})

    @staticmethod
    def gen_token():
        # 实例认证对象
        qi = Auth(access_key,secret_key)
        # 生成上传token
        token = qi.upload_token('hancj')  # 传入存储空间的名字
        return token




















